#include "workhisform.h"
#include "ui_workhisform.h"

WorkHisForm::WorkHisForm(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::WorkHisForm)
{
    ui->setupUi(this);

    // 注册自定义类型
    qRegisterMetaType<T_BatchLine>("T_BatchLine");
    qRegisterMetaType<QList<T_BatchLine>>("QList<T_BatchLine>&");

    m_calcAvgWork = new WorkHisAvgThread;
    m_calcThread = new QThread;
    m_calcAvgWork->moveToThread(m_calcThread);
    m_calcThread->start();

    // 初始化弹窗
    m_pMsg = new Message(this);


    ui->label_btime->hide();
    ui->LE_beginTime->hide();
    ui->label_etime->hide();
    ui->LE_endTime->hide();
    ui->btn_query->hide();


    // 隐藏客户
    // ui->customerName->hide();
    // ui->LE_customer->hide();

    // 隐藏分页表格显示功能
    ui->btn_nextPage->hide();
    ui->btn_prePage->hide();
    ui->label_page->hide();

    ui->LE_customer->setReadOnly(true);
    ui->LE_batchName->setReadOnly(true);

    init_connectSigSlot();

    //connect(ui->tableWidget->verticalScrollBar(), SIGNAL(valueChanged(int)),this,SLOT(OnSlideAction(int)));//响应滚动条翻页
    QFile file(":/qss/dlg.qss");
    if (file.open(QFile::ReadOnly))
    {
        QTextStream filetext(&file);
        QString stylesheet = filetext.readAll();
        this->setStyleSheet(stylesheet);
        file.close();
    }


    ui->label_tabTitle_icon->setPixmap(QPixmap(":/imgs/hiswd_img_1.png"));
    ui->label_imgTitle_icon->setPixmap(QPixmap(":/imgs/hiswd_img_2.png"));
    ui->label_tabTitle_icon->setScaledContents(true);
    ui->label_imgTitle_icon->setScaledContents(true);

    ui->tableWidget->setShowGrid(true);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    ui->tableWidget->verticalHeader()->hide();//取消默认行号

    m_header  << tr("id") << tr("detect_time")
            << tr("wood_type") << tr("wood_processing")         // 种类， 加工方式
            << tr("wood_ok_rate(%)") << tr("wood_length(mm)")   // 正材率(%)， 长度(mm)
            << tr("wood_width(mm)") << tr("wood_area(mm²)")     // 宽度(mm)， 木材面积(mm²)
            << tr("wood_dk(%)") << tr("wood_lk(%)")             // 死结(%)，活结(%)
            << tr("wood_ck(%)") << tr("wood_pith(%)")           // 裂纹(%)， 髓芯(%)
            << tr("wood_em(%)") << tr("wood_wh(%)")           // 缺损(%)， 虫孔(%)
            << tr("wood_sm(%)") << tr("wood_bd(%)")           // 矿物线(%)， 鸟啄(%)
            << tr("wood_pt(%)") << tr("wood_rs(%)");           // 胶水(%)， 毛面(%)
    ui->tableWidget->setColumnCount(m_header.size());
    ui->tableWidget->setHorizontalHeaderLabels(m_header);

    //自动调整窗口列表的【宽、高】---适应窗口大小
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    for(int i{2}; i < m_header.count(); i++)
        ui->tableWidget->setColumnWidth(i,m_header.at(i).size() * 20 + 10);

    ui->tableWidget->setColumnWidth(0,55);
    ui->tableWidget->setColumnWidth(1,QString("0000-00-00 00:00:00").size() * 10 + 30);


    QGraphicsDropShadowEffect *shadow_effectA = new QGraphicsDropShadowEffect(this);
    QGraphicsDropShadowEffect *shadow_effectB = new QGraphicsDropShadowEffect(this);
    QGraphicsDropShadowEffect *shadow_effectC = new QGraphicsDropShadowEffect(this);

    shadow_effectA->setOffset(0, 0);
    shadow_effectA->setColor(QColor(150,150,150));
    shadow_effectA->setBlurRadius(6);

    shadow_effectB->setOffset(0, 0);
    shadow_effectB->setColor(QColor(150,150,150));
    shadow_effectB->setBlurRadius(6);

    shadow_effectC->setOffset(0, 0);
    shadow_effectC->setColor(QColor(150,150,150));
    shadow_effectC->setBlurRadius(6);

    ui->Data_gBox_1->setGraphicsEffect(shadow_effectA);
    ui->Data_gBox_2->setGraphicsEffect(shadow_effectB);
    ui->Data_gBox_3->setGraphicsEffect(shadow_effectC);

    //允许绘制背景色交替 必须写这句否则交替背景色没有效果
    ui->tableWidget->setAlternatingRowColors(true);

    clearTableWidget();

}

WorkHisForm::~WorkHisForm()
{
    delete ui;
    qDebug() << "    ~WorkHisForm()";
}

void WorkHisForm::updateHistoryData()
{
    // for(int i{2}; i < m_header.count(); i++)
    //     ui->tableWidget->setColumnWidth(i,m_header.at(i).size() * 10 + 10);

    // ui->tableWidget->setColumnWidth(0,55);
    // ui->tableWidget->setColumnWidth(1,QString("0000-00-00 00:00:00").size() * 10 + 30);



    QDateTime beginTime = QDateTime::fromString(ui->LE_beginTime->text(),"yyyy-MM-dd_hh:mm:ss");
    QDateTime endTime = QDateTime::fromString(ui->LE_endTime->text(),"yyyy-MM-dd_hh:mm:ss");

    if(beginTime.secsTo(endTime) <= 0)
    {
        m_pMsg->Push(MESSAGE_TYPE_WARNING, tr("Time Error!"));  // "输入时间错误！"
        return;
    }

    m_ImgPathMap.clear();
    m_HisDataList.clear();

    SqliteUtil m_sql;
    m_sql.init("BatchCreate_db");
    m_HisDataList = m_sql.queryBatchLines(m_currBatchID);

    if(m_HisDataList.count() == 0) return;

    // 计算平均值
    emit signal_CalcAvg(m_HisDataList);

    setTableData(m_HisDataList);

    // // 初始化表格翻页
    // ui->btn_prePage->setEnabled(false);
    // ui->btn_nextPage->setEnabled(true);

    // // 总页数 = 数据总数 / 每页多少条数据 + 1
    // m_toalPageNum = m_HisDataList.count() / _PAGE_NUM_ + 1;
    // m_currPageNum = 1;

    // // 默认设置第一页
    // if(m_HisDataList.count())


}

void WorkHisForm::clearTableWidget()
{
    ui->tableWidget->setRowCount(0);


    // 初始化提示

    ui->data_1->setText(QString(tr("Total: ")));            // "总数: "
    ui->data_3->setText(QString(tr("AvgOkRate: ")))   ;     // "平均正确率: "
    ui->data_4->setText(QString(tr("TotalLength: "))) ;     // "总长度: "
    ui->data_5->setText(QString(tr("TotalWidth: ")))  ;     // "总宽度: "
    ui->data_6->setText(QString(tr("TotalArea: ")))   ;     // "总面积: "
    ui->data_7->setText(QString(tr("AvgDKRate: ")))   ;     // "平均死结: "
    ui->data_8->setText(QString(tr("AvgLKRate: ")))   ;     // "平均活结: "
    ui->data_9->setText(QString(tr("AvgCRRate: ")))   ;     // "平均裂纹: "
    ui->data_10->setText(QString(tr("AvgHBRate: "))) ;    // "平均髓芯: "
    ui->data_11->setText(QString(tr("AvgEMRate: "))) ;      // "平均缺损: "
    ui->data_12->setText(QString(tr("AvgWHRate: "))) ;      // "平均虫孔: "
    ui->data_13->setText(QString(tr("AvgSMRate: "))) ;      // "平均矿物线: "
    ui->data_14->setText(QString(tr("AvgBDRate: "))) ;      // "平均鸟啄: "
    ui->data_15->setText(QString(tr("AvgPTRate: "))) ;      // "平均胶水: "
    ui->data_16->setText(QString(tr("AvgRSRate: "))) ;      // "平均毛面: "
}

void WorkHisForm::setBatchIDName(int id, QString batchName)
{
    m_currBatchID = id;
    m_currBatchName = batchName;
    ui->LE_batchName->setText(m_currBatchName);
}

void WorkHisForm::setCustomerName(QString name)
{
    ui->LE_customer->setText(name);
}

void WorkHisForm::OnSlideAction(int nRowIndex)
{

}

void WorkHisForm::init_connectSigSlot()
{
    connect(ui->tableWidget,&QTableWidget::cellDoubleClicked,this,[this](int row, int column)
    {
        QTableWidgetItem* item = ui->tableWidget->item(row ,0);
        QTableWidgetItem* item_time = ui->tableWidget->item(row ,1); // 不确定是不是第0列，可能需要修改
        if(item == nullptr || item_time == nullptr)
        {
            ui->label_imgTime->setText("");
            clearTableWidget();
            return;
        }
        m_CurTabItemID = item->text();

        // TODO 根据得到的id 获取图片路径, 并且设置 label_imgTime 控件的时间显示

        QList<QString> list = readJsonPath(m_ImgPathMap.value(m_CurTabItemID.toInt()));
        for(int i{}; i < list.count(); i++)
            setWoodImage(i + 1,list[i]);

        ui->label_imgTime->setText(item_time->text());
    });

    connect(this,&WorkHisForm::signal_CalcAvg,m_calcAvgWork,&WorkHisAvgThread::working);

    connect(m_calcAvgWork,&WorkHisAvgThread::signal_calcSeccsess, this, [this](T_BatchLine avgData)
    {
        if(avgData.id == -1)
        {
            clearTableWidget();
            return;
        }

        ui->data_3->setText(QString(tr("AvgOkRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_ok_rate)));             // "平均正确率: %1 %"
        ui->data_4->setText(QString(tr("TotalLength: %1 m")).arg(QString::asprintf("%.2f",avgData.wood_length / 100)));      // "总长度: %1 m"
        ui->data_5->setText(QString(tr("TotalWidth: %1 m")).arg(QString::asprintf("%.2f",avgData.wood_width / 100)));        // "总宽度: %1 m"
        ui->data_6->setText(QString(tr("TotalArea: %1 m²")).arg(QString::asprintf("%.2f",avgData.wood_wood_area / 1000000)));     // "总面积: %1 m²"
        ui->data_7->setText(QString(tr("AvgDKRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_dk)));                  // "平均死结: %1 %"
        ui->data_8->setText(QString(tr("AvgLKRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_lk)));                  // "平均活结: %1 %"
        ui->data_9->setText(QString(tr("AvgCRRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_cr)));                  // "平均裂纹: %1 %"
        ui->data_10->setText(QString(tr("AvgHBRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_hb)));             // "平均髓芯: %1 %"
        ui->data_11->setText(QString(tr("AvgEMRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_em)));                 // "平均缺损: %1 %"
        ui->data_12->setText(QString(tr("AvgWHRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_wh)));                 // "平均虫孔: %1 %"
        ui->data_13->setText(QString(tr("AvgSMRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_sm)));                 // "平均矿物线: %1 %"
        ui->data_14->setText(QString(tr("AvgBDRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_bd)));                 // "平均鸟啄: %1 %"
        ui->data_15->setText(QString(tr("AvgPTRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_pt)));                 // "平均胶水: %1 %"
        ui->data_16->setText(QString(tr("AvgRSRate: %1 %")).arg(QString::asprintf("%.2f",avgData.wood_rs)));                 // "平均毛面: %1 %"
    });

    // 查询按钮
    //connect(ui->btn_query,&QPushButton::clicked,this,&WorkHisForm::updateHistoryData);

    // // 上一页
    // connect(ui->btn_prePage,&QPushButton::clicked,this,[this]()
    // {

    // });
    // // 下一页
    // connect(ui->btn_nextPage,&QPushButton::clicked,this,[this]()
    // {

    // });
}

void WorkHisForm::setTableData(const QList<T_BatchLine> &list)
{
    if(list.isEmpty()) return;

    ui->tableWidget->setRowCount(0);

    ui->tableWidget->setRowCount(list.count());

    for(int i{}; i < ui->tableWidget->rowCount(); ++i)
    {
        m_ImgPathMap.insert(list[i].id,list[i].cam_img_json);
        ui->tableWidget->setItem(i, 0, new QTableWidgetItem(QString::number(list[i].id)));
        ui->tableWidget->setItem(i, 1, new QTableWidgetItem(list[i].create_time));
        ui->tableWidget->setItem(i, 2, new QTableWidgetItem(list[i].wood_type));
        ui->tableWidget->setItem(i, 3, new QTableWidgetItem(list[i].wood_processing));

        // 正材率用进度条
        ProgressBarWidget *p = new ProgressBarWidget;
        p->setValue(list[i].wood_ok_rate);
        ui->tableWidget->setCellWidget(i,4,p);
        //ui->tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(list[i].wood_ok_rate)));
        ui->tableWidget->setItem(i, 5, new QTableWidgetItem(QString::number(list[i].wood_length)));
        ui->tableWidget->setItem(i, 6, new QTableWidgetItem(QString::number(list[i].wood_width)));
        ui->tableWidget->setItem(i, 7, new QTableWidgetItem(QString::number(list[i].wood_wood_area)));
        ui->tableWidget->setItem(i, 8, new QTableWidgetItem(QString::number(list[i].wood_dk)));
        ui->tableWidget->setItem(i, 9, new QTableWidgetItem(QString::number(list[i].wood_lk)));
        ui->tableWidget->setItem(i, 10, new QTableWidgetItem(QString::number(list[i].wood_cr)));
        ui->tableWidget->setItem(i, 11, new QTableWidgetItem(QString::number(list[i].wood_hb)));
        ui->tableWidget->setItem(i, 12, new QTableWidgetItem(QString::number(list[i].wood_em)));
        ui->tableWidget->setItem(i, 13, new QTableWidgetItem(QString::number(list[i].wood_wh)));
        ui->tableWidget->setItem(i, 14, new QTableWidgetItem(QString::number(list[i].wood_sm)));
        ui->tableWidget->setItem(i, 15, new QTableWidgetItem(QString::number(list[i].wood_bd)));
        ui->tableWidget->setItem(i, 16, new QTableWidgetItem(QString::number(list[i].wood_pt)));
        ui->tableWidget->setItem(i, 17, new QTableWidgetItem(QString::number(list[i].wood_rs)));

        // 设置居中对其
        for(int j{}; j < ui->tableWidget->columnCount(); ++j)
        {
            if(j == 4) continue;    // 第四列是进度条widget，不需要特意设置居中

            ui->tableWidget->item(i,j)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
        }
    }

    // TODO 总数是由 表格的行数(可能分页显示) / 数据库给的数据总数
    ui->data_1->setText(QString(tr("Total: %1")).arg(ui->tableWidget->rowCount()));     // "总数: %1"
}

void WorkHisForm::setWoodImage(int index, const QString &ImagePath)
{
    if(ImagePath == "" | index == 0) return;

    QImage image;
    if(!image.load(ImagePath))
    {
        image = QImage(ui->label_woodImage_1->size(), QImage::Format_RGB888);
        image.fill(Qt::black);
    }
    else
    {
        //image = image.scaled(this->ui->label_woodImage_1->size(),Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    }

    // TODO 显示图像可能会有问题，看情况调整

    switch(index)
    {
        case 1:
        {
            ui->label_woodImage_1->setPixmap(QPixmap::fromImage(image));
            break;
        }
        case 2:
        {
            ui->label_woodImage_2->setPixmap(QPixmap::fromImage(image));
            break;
        }
        case 3:
        {
            ui->label_woodImage_3->setPixmap(QPixmap::fromImage(image));
            break;
        }
        case 4:
        {
            ui->label_woodImage_4->setPixmap(QPixmap::fromImage(image));
            break;
        }
    }

}

QList<QString> WorkHisForm::readJsonPath(const QString &fileName)
{
    QStringList list = fileName.split(';');
    QList<QString> lis;
    for(int i{}; i < list.count(); i++)
        lis.append("." + list[i]);

    return lis;
}

WorkHisAvgThread::WorkHisAvgThread(QObject *parent): QObject(parent)
{

}

void WorkHisAvgThread::working(QList<T_BatchLine> &list)
{
    T_BatchLine data;
    if (list.isEmpty())
    {
        emit signal_calcSeccsess(data);
        return;
    }

    data.id = 0;
    for(int i{}; i < list.count(); ++i)
    {
        data.wood_ok_rate   += list.at(i).wood_ok_rate;
        data.wood_length    += list.at(i).wood_length;
        data.wood_width     += list.at(i).wood_width;
        data.wood_wood_area      += list.at(i).wood_wood_area;
        data.wood_dk        += list.at(i).wood_dk;
        data.wood_lk        += list.at(i).wood_lk;
        data.wood_cr        += list.at(i).wood_cr;
        data.wood_hb        += list.at(i).wood_hb;
        data.wood_em        += list.at(i).wood_em;
        data.wood_wh        += list.at(i).wood_wh;
        data.wood_sm        += list.at(i).wood_sm;
        data.wood_bd        += list.at(i).wood_bd;
        data.wood_pt        += list.at(i).wood_pt;
        data.wood_rs        += list.at(i).wood_rs;
    }

    // 计算平均值，总数不用计算
    data.wood_ok_rate   /= list.count();
    data.wood_dk        /= list.count();
    data.wood_lk        /= list.count();
    data.wood_cr        /= list.count();
    data.wood_hb        /= list.count();
    data.wood_em        /= list.count();
    data.wood_wh        /= list.count();
    data.wood_sm        /= list.count();
    data.wood_bd        /= list.count();
    data.wood_pt        /= list.count();
    data.wood_rs        /= list.count();

    emit signal_calcSeccsess(data);
}

MyScrollArea::MyScrollArea(QWidget *parent)
    : QScrollArea{parent}
{
}

void MyScrollArea::wheelEvent(QWheelEvent *event)
{
}
